from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

class CommaSeparatedUserWidget(forms.TextInput):
    """
    A text input with comma separated usernames
    """
    def __init__(self, attrs=None, render_value=True):
        self.attrs = {'size': '40'}
        if attrs:
            self.attrs.update(attrs)

    def render(self, name, values, attrs=None):
        names = []
        if values:
            if isinstance(values[0], int):
                names = [u.username for u in User.objects.filter(pk__in=values)]
            else:
                for value in values:
                    names.append(value)
            values = ", ".join(names)
        else:
            values = ""
        return super(CommaSeparatedUserWidget,self).render(name, values, attrs)
    
    
    def value_from_datadict(self, data, files, name):
        names = [name.strip() for name in data[name].split(",") if name]
        return names
    
    
class UserField(forms.CharField):
    """
    Field for many2many relations to Users without showing
    a list of all users
    """
    widget = CommaSeparatedUserWidget

    def clean(self, names):
        if names:
            users = []
            not_found = []
            for name in names:
                try:                
                    users.append(User.objects.get(username=name).id)
                except ObjectDoesNotExist:
                    not_found.append(name)
            if not_found:
                invalid_users = ", ".join(not_found)                
                raise forms.ValidationError("Could not find user%s: %s" % 
                                    (pluralize(not_found,"s"),invalid_users))
            return users
        else:
            if self.required:
                raise forms.ValidationError(self.error_messages['required'])
            else:
                return None